'use strict';
var fs=require('fs');

const Controller = require('egg').Controller;
const cheerio = require('cheerio')
class DemoController extends Controller {
  async index() {
	var ctx = this.ctx;
	const data = await ctx.service.spider.getData();
	const $ = cheerio.load(data.data);
	const objectMenu = [];
	let url = 'http://wiki.joyme.com';
	var jsonstr2 = "";
	let jsonstr = "";
	let Menujsonstr = "";
	$(".MenuBox li").each(function(i){
		let o = {kind:i,name:$(this).text()};
		objectMenu.push(o);
		Menujsonstr += "{kind:'"+i+"',name:'"+$(this).text()+"'}";
	});
	const objectList = [];
	$("#Contentbox2 div[id^='con_']").each(function(){
		let id = $(this).attr("id");
		var item = {id:id,list:[]};
		$(this).find(".wikitable").each(function(i){
			let href = url + $(this).find("a").eq(0).attr("href");
			let name = $(this).find("tr").eq(1).find("a").text()
			let obj = {src:$(this).find("img").eq(0).attr("src"),name:name}
			item.list.push(obj);
			jsonstr += "{src:'"+$(this).find("img").eq(0).attr("src")+"',name:'"+$(this).find("tr").eq(1).find("a").text()+"'}";
		});
		objectList.push(item);
	});
	let ob = {menu:objectMenu,people:objectList};
	await ctx.render('list.tpl', ob);
	var m = 0;
	var n = 0;
	fs.mkdir('txt',function(error){
		if(error){
			console.log(error);
			return false;
		}
		console.log('创建目录成功');
	})
	fs.writeFile('txt/jsonMenu.json',Menujsonstr,'utf8',function(error){
		if(error){
			console.log(error);
			return false;
		}
		console.log('写入成功');
	});
	fs.writeFile('txt/jsonicon.json',jsonstr,'utf8',function(error){
		if(error){
			console.log(error);
			return false;
		}
		console.log('写入成功');
	});
	
	let NewsList = "";
	let NewsTitleAry = [];
	const newsdata = await ctx.service.spider.getNew();
	const $n = cheerio.load(newsdata.data);
	$n("#mw-content-text table a").each(function(){
		let title = $(this).text();
		let href = $(this).attr("href");
		let html = "";
		NewsTitleAry.push(title.replace(" ","_"));
	});
	let NewsTitleAryI = 0;
	newsTime();
	async function newsTime(){
		if(NewsTitleAryI>=NewsTitleAry.length){
			oneTime();
			return;
		}
		const Detail = await ctx.service.spider.getDetail(NewsTitleAry[NewsTitleAryI]);
		const $d1 = cheerio.load(Detail.data);
		if($d1("#mw-content-text").length>0){
			let imgStr = "";
			$d1("#mw-content-text").find("img").each(i => {
				imgStr += $d1("#mw-content-text").find("img").eq(i).attr("src");
				imgStr = i === ($d1("#mw-content-text").find("img").length-1)?imgStr:(imgStr+",");
			});
			console.info(imgStr);
			let html = $d1("#mw-content-text").html();
			NewsList+='{title:"'+NewsTitleAry[NewsTitleAryI]+'",html:"'+encodeURIComponent(html.replace(/[\r\n]/g,"").replace(/<!--(.*?)-->/g,"").replace(/<style\>(.*?)\<\/style>/g,""))+'",imgStr:"'+imgStr+'"}';
			console.log(1,NewsTitleAry[NewsTitleAryI],NewsTitleAryI);
			fs.writeFile('txt/jsonnews.json',NewsList,'utf8',function(error){
				if(error){
					console.log(error);
					return false;
				}
			});
			NewsTitleAryI++
		}else{
			NewsList+="{title:'"+NewsTitleAry[NewsTitleAryI]+"',html:'',imgStr:''}";
			console.log(3,NewsTitleAry[NewsTitleAryI],NewsTitleAryI);
			fs.writeFile('txt/jsonnews.json',NewsList,'utf8',function(error){
				if(error){
					console.log(error);
					return false;
				}
			});
			NewsTitleAryI++
		}
		setTimeout(()=>{newsTime()},1000)
	}
	async function oneTime(){
		if(m>=objectList.length){
			//console.info("end");
			//clearInverval(oneTime);
			return;
		}
		var name = objectList[m].list[n].name;
		const data = await ctx.service.spider.getDetail(name);
		const $d = cheerio.load(data.data);
		let zt = $d(".zt").text().trim();
		const objectImg = []
		var objectImgJson = "";
		$d(".mwiki_hide .MenuBox li").each(function(i){
			let o = {kind:$(this).text(),src:$("#Contentbox2 #con_"+i).find("img").attr("src")};
			objectImg.push(o);
			let string = '{"kind":"'+$(this).text()+'","src":"'+
			$d("#Contentbox2 div[id^='con_'] img").eq(i).attr("src")+'"}';
			if(i!=$d(".mwiki_hide .MenuBox li").length-1)
				string+=';';
			objectImgJson += string;
		});
		let jnstr = "";
		let dastr = "";
		$d(".tj-bg-left .tj-bgs").each(function(i){
			jnstr += ",jn"+i+":'"+$d(this).html().replace(/[\r\n]/g,"")+"'";
		});
		$d(".tj-bg-right .tj-bgs").each(function(i){
			dastr += ",da"+i+":'"+$d(this).html().replace(/[\r\n]/g,"")+"'";
		});
		objectImgJson = ",imgObject:'"+objectImgJson+"'";
		let string =  "{name:'"+name+"',zt0:'"+$d(".mwiki_hide .tj-bg").eq(0).html().replace(/[\r\n]/g,"")
		+"',zt1:'"+$d(".mwiki_hide .tj-bg").eq(1).html().replace(/[\r\n]/g,"")
		+"',zt2:'"+$d(".mwiki_hide .tj-bg").eq(2).html().replace(/[\r\n]/g,"")
		+"',zt3:'"+$d(".mwiki_hide .tj-bg").eq(3).html().replace(/[\r\n]/g,"")+"'"
		+jnstr+dastr
		+objectImgJson+"}";
		jsonstr2+=string;
		/*fs.writeFile('txt/'+name+'.txt',string,'utf8',function(error){
			if(error){
				console.log(error);
				return false;
			}
			console.log(name,zt)
			console.log('写入成功');
		})*/
		fs.writeFile('txt/json.json',jsonstr2,'utf8',function(error){
			if(error){
				console.log(error);
				return false;
			}
			console.log(name)
			//console.log('写入成功');
		})
		if(n==objectList[m].list.length-1){
			m++;n=0;
		}else{
			n++;
		}
		/*if(m >= objectList.length){
			console.info("end");
			clearInverval(oneTime);
		};*/
		setTimeout(()=>{oneTime()},3000)
	};
  }
  async content(name) {
	const data = await this.ctx.service.spider.getDetail(name);
	const $d = cheerio.load(data.data);
	let zt = $(".zt").text();
	let string =  "{name:'"+name+"',zt:'"+zt+"'}";
	jsonstr2 += string;
  }
}

module.exports = DemoController;
